import React, { memo, useState, useEffect, useRef } from 'react';
import { Toast, Modal, Dialog, Input, Calendar, Image } from 'antd-mobile'
import HeadTop from '@/components/HeadTop';
import SelectCalendar from '@/components/SelectCalendarTime';
import { validatenull } from "@/utils/validate";
import { dateTimeFormatter } from "@/utils/utils";
import ListItem from '../_parts/ListItem';
import ApiIndex from '@/api/maintenance';
import Loading from '@/components/Loading';
import "./index.less"

import { MyContext } from '@/context/index';
const { Provider, Consumer } = MyContext

const TabLine = memo(({ setTabStatus }) => {
    const [status, setStatus] = useState('0') //0未处理 1处理中
    const changeSelect = (val) => {
        setStatus(val)
        setTabStatus(val)
    }
    return (
        <div className='tabLine'>
            <div onClick={() => { changeSelect('0') }}
                className={'tabTxt' + ' ' + (status == '0' ? 'tabActive' : '')} >
                <span className={'tabTxt' + ' ' + (status == '0' ? 'tabActive' : '')}>未处理</span>
            </div>
            <div onClick={() => { changeSelect('1') }} className={'tabTxt' + ' ' + (status == '1' ? 'tabActive' : '')} >
                <span className={'tabTxt' + ' ' + (status == '1' ? 'tabActive' : '')}>处理中</span>
            </div>
        </div>
    )
})

const CancelPop = memo(({ setTxt }) => {
    const [cancelTxt, setCancelTxt] = useState('');
    return (
        <div className="cancel-modal" >
            <p style={{fontSize: 12}}>取消原因</p>
            <Input
                style={{ height: 45,fontSize: 12 }}
                placeholder='请输入内容'
                value={cancelTxt}
                onChange={val => {
                    setTxt(val)
                    setCancelTxt(val)
                }}
            />
        </div>
    )
})
const EditTime = memo((props) => {
    const [valueTime, setValueTime] = useState(new Date());
    const [editTxt, setEditTxt] = useState('');
    const canlendar = useRef(null)

    const changeCalendar = () => {
        canlendar.current.changeVisivle()
    }
    const getCanlendarVal = (val) => {
        setValueTime(val)
    }

    useEffect(() => {
        props.sendTimeTxt(valueTime, editTxt)

    }, [valueTime, editTxt])

    return (
        <div className="cancel-modal">
            <div className="time-line">
                <span  style={{ fontSize: 12 }}>选择时间：</span>
                <span  style={{ fontSize: 12 }} onClick={changeCalendar}>{dateTimeFormatter(valueTime, 'yyyy-MM-dd hh:mm')}</span>
            </div>
            <div className="reason-line">
                <Input
                    style={{ height: 45 }}
                    placeholder='请输入原因'
                    value={editTxt}
                    onChange={val => {
                        setEditTxt(val)
                    }}
                />
            </div>

            <SelectCalendar ref={canlendar} getCanlendarVal={getCanlendarVal}></SelectCalendar>
        </div>
    )
})

function Index({ history }) {
    const [inputVal, setInputVal] = useState('');

    const [List, setList] = useState([]); //列表
    const [hasMore, setHasMore] = useState(true) //上拉
    const [pageNum, setPageNum] = useState(1) //页码
    const [statusVal, setStatusVal] = useState('WAIT_FINISH') //初始未处理
    const [timeVal, setTimeVal] = useState()
    const [loading, setLoading] = useState(false);

    let timeref = useRef('')
    // 定义防抖函数
    const getRequest = async (change, value) => {
        setLoading(true)
        let params = {
            page: 1,
            size: 100,
            type: 'MAINTAIN',
            status: statusVal,
            deviceCode: value ? value : ''
        }

        let res = null;
        if (!value) {
            res = await ApiIndex.getList(params)
        } else {
            res = await ApiIndex.searchKey(params)
        }
        setLoading(false)
        if (res.data.code) {
            Toast.show({
                content: '请求失败:' + res.data.msg,
            })
            return
        }

        if (value) {
            let list = res.data.data.records
            setList(list)
            return
        }


        if (res.data.data.records.length) {

            let list = res.data.data.records
            if (change) {
                setList(list)
            } else {
                setList(List.concat(list))
            }
            setHasMore(true)
            setPageNum(pageNum + 1)
        }
        if (res.data.data.current == res.data.data.pages || !res.data.data.pages) {
            setHasMore(false)
        }
    }

    // 搜索
    const sendHandlePressVal = (value) => {
        if (validatenull(value)) return
        let _value = value
        if (value.indexOf("*") != -1) {
            _value = value.split("*")[0]
        }
        setInputVal(_value)

        handleDebounce(_value, List)
    }
    const handleDebounce = (value, list) => {

        getRequest('', value)
    }

    // tab切换
    const setTabStatus = (st) => {
        setList([])
        setInputVal('')
        setPageNum(1)
        if (st == '0') {
            setStatusVal('WAIT_FINISH')
        }

        if (st == '1') {
            setStatusVal('PROCESSING')
        }
    }
    useEffect(() => {
        getRequest('change')
    }, [statusVal])



    // 取消 修改
    const cancel = async (e, no) => {
        e.stopPropagation()
        Dialog.confirm({
            content: <CancelPop setTxt={txt => useRef.current = txt}></CancelPop>,
            onConfirm: async () => {
                putList(useRef.current, no, 'CANCEL')
            },
        })
    }
    const edit = (e, no) => {
        e.stopPropagation()
        Dialog.confirm({
            content: <EditTime sendTimeTxt={(time, txt) => getEditInfo(time, txt)}></EditTime>,
            onConfirm: async () => {
                putList(useRef.current, no, 'CHANGE')
            },
        })
    }
    const getEditInfo = (time, txt) => {
        setTimeVal(time)
        timeref.current = time
        useRef.current = txt
    }

    const putList = (reason, no, type) => {
        console.log(timeref.current,'timeref.current')
        let params = {
            cancelReason: reason,
            inspectionNo: no,
            applyType: type,
            changeTime: dateTimeFormatter(new Date(timeref.current), 'yyyy-MM-dd hh:mm:ss') 
        }
        ApiIndex.getChangeApply(params).then(res => {
            if (res.data.code == 0) {
                Toast.show({
                    content: '操作成功:'
                })
                getRequest('')
            } else {
                Toast.show({
                    content: res.data.msg
                })
            }
        })
    }

    return (
        <div className='page-wrapper'>
            {
                loading ? <Loading></Loading> : null
            }
            <Provider value={{ placeholderTxt: "请输入保养编号", inputVal: inputVal }}>
                <HeadTop
                    title="设备保养"
                    rightTxt="保养记录"
                    history={history}
                    search={true}
                    getHandleRight={() => history.push("/maintenanceRecord")}
                    sendHandlePressVal={sendHandlePressVal}
                ></HeadTop>
            </Provider>
            <TabLine setTabStatus={setTabStatus}></TabLine>
            <div className="page-body" style={{ padding: 15 }}>
                {
                    !List?.length ?
                        <div className='no-list-data'>
                            无更多数据
                        </div> : (
                            List.map(el =>
                                <ListItem
                                    item={el}
                                    cancel={cancel}
                                    edit={edit}
                                    history={history}
                                    key={el.id}>
                                </ListItem>)
                        )
                }
            </div>
        </div>
    );
}

export default Index;
